/*
	File:	TextureManager.cpp
	Author:	TJ Ashby
	
	Comments:	Handles all images/textures for our game and can manipulate them.
*/

#include "TextureManager.h"
#include "D3DManager.h"

TextureManager::TextureManager(void)
{
	spriteManager = nullptr;
	d3dDevice = nullptr;

	textureList.clear();
}


TextureManager::~TextureManager(void)
{
}

TextureManager* TextureManager::getInstance()
{
	static TextureManager instance;
	return &instance;
}

void TextureManager::Initialize()
{
#ifdef _DEBUG
	cout << "Initializing Texture Manager...";
#endif

	if(!d3dDevice)
		d3dDevice = D3DManager::getInstance()->getDevice();

	if(!spriteManager)
		D3DXCreateSprite(d3dDevice,&spriteManager);

#ifdef _DEBUG
	cout << " Complete\n";
#endif
}

void TextureManager::Shutdown()
{
#ifdef _DEBUG
	cout << "Shutting Down Texture Manager...";
#endif
	for(unsigned i = 0;i < textureList.size();++i)
		SAFE_RELEASE(textureList[i]);

	textureList.clear();
	SAFE_RELEASE(spriteManager);

	d3dDevice = nullptr;

#ifdef _DEBUG
	cout << " Complete\n";
#endif
}

void TextureManager::Draw( int ImageID,Vector2 Position,Vector2 Center /*= Vector2(0,0)*/,const RECT *Section,
	float Rotation,Vector2 Scale /*= Vector2(1,1)*/,Color color /*= Color(1,1,1,1)*/ )
{
	Matrix matrix;
	TranslateMatrix(matrix,Position.x,Position.y,0);

	Matrix scaling;
	D3DXMatrixScaling(&scaling,Scale.x,Scale.y,0);

	Matrix rot;
	RotateZ(rot,Rotation);
	matrix = rot * matrix;

	// Set the location of the sprite
	spriteManager->SetTransform(&(matrix*scaling));
	spriteManager->Draw(textureList[ImageID],Section,&Vector3(Center.x,Center.y,0),&Vector3(0,0,0),color);
}

int TextureManager::LoadTexture( String Destination )
{
	IDirect3DTexture9 *texture = nullptr;

	if(FAILED(D3DXCreateTextureFromFileA(d3dDevice,Destination,&texture)))
		return -1;

	textureList.push_back(texture);

	return textureList.size()-1;
}

void TextureManager::BeginDraw()
{
	spriteManager->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_DEPTH_BACKTOFRONT);
}

void TextureManager::EndDraw()
{
	spriteManager->End();
}

void TextureManager::UnloadTexture( int ImageID )
{
	if(ImageID >= 0)
	{
		SAFE_RELEASE(textureList[ImageID]);
		textureList[ImageID] = nullptr;

		/*std::vector<IDirect3DTexture9*>::iterator iter;
		iter = textureList.begin();

		for(int i = 0;i != ImageID;++i,++iter);

		textureList.erase(iter);*/
	}
}

void TextureManager::Flush()
{
	spriteManager->Flush();
}

